import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:lmmi/common/index.dart';
import 'package:lmmi/view/share_detail/widget/gift_dialog_widget.dart';
import '../../common/widgets/lazy_video_player_widget.dart';
import '../../common/services/viewer_service.dart';

class ShareDetailPage extends ConsumerStatefulWidget {
  const ShareDetailPage({super.key});

  @override
  ConsumerState<ShareDetailPage> createState() => _ShareDetailPageState();
}

class _ShareDetailPageState extends ConsumerState<ShareDetailPage> {
  final _scrollController = ScrollController();
  final _commentController = TextEditingController();
  final _focusNode = FocusNode();

  String? shareId;
  ShareEntity? currentShare;
  UserEntity? shareAuthor;
  List<CommentEntity> comments = [];
  List<UserEntity> viewers = [];
  bool isLiked = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeData();
    });
  }

  @override
  void dispose() {
    _commentController.dispose();
    _focusNode.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 初始化数据
  void _initializeData() {
    // 获取路由参数
    final extra = GoRouterState.of(context).extra as Map<String, dynamic>?;
    shareId = extra?['shareId'] as String?;

    if (shareId != null) {
      _loadShareData();
    }
  }

  /// 加载分享数据
  Future<void> _loadShareData() async {
    if (shareId == null) return;

    try {
      // 获取分享详情
      final shares = await ShareService.getSharesById(shareId!);
      if (shares.isNotEmpty) {
        currentShare = shares.first;

        // 获取分享作者
        shareAuthor = ShareService.getShareAuthor(currentShare!);

        // 获取评论
        comments = await CommentService.getCommentsByShareId(shareId!);

        // 按时间降序排序（最新的在前面）
        comments.sort(
          (a, b) => DateTime.parse(b.date).compareTo(DateTime.parse(a.date)),
        );

        // 获取浏览者（详情页中当前用户肯定浏览过）
        final currentUser = ref.read(currentUserProvider);
        viewers = ViewerService.getShareDetailViewers(
          shareId: shareId!,
          browseCount: currentShare!.browses,
          currentUserId: currentUser?.id,
        );

        // 检查当前用户是否已点赞
        if (currentUser != null) {
          isLiked = currentUser.like.contains(shareId);
        }

        setState(() {});
      }
    } catch (e) {
      debugPrint('加载分享数据失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (currentShare == null) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFF363633),
          elevation: 0,
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.white),
            onPressed: () {
              if (Navigator.canPop(context)) {
                Navigator.pop(context);
              } else {
                context.go(AppRoutes.main);
              }
            },
          ),
        ),
        body: Container(
          color: Color(0xFF363633),
          child: Center(child: CircularProgressIndicator(color: Colors.white)),
        ),
      );
    }

    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Color(0xFF363633),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.white),
          onPressed: () {
            if (Navigator.canPop(context)) {
              context.goBack();
            } else {
              context.go(AppRoutes.main);
            }
          },
        ),
        actions: [
          IconButton(
            icon: Image.asset(MyImages.gift, width: 38.w, height: 38.h),
            onPressed: _showGiftDialog,
          ),
          IconButton(
            icon: SvgPicture.asset(MyIcons.report, width: 28.w, height: 28.h),
            onPressed: _showReportDialog,
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () {
          _focusNode.unfocus();
        },
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          color: const Color(0xFF363633),
          child: Stack(
            children: [
              // 主要内容区域
              Container(
                width: 351.w,
                height:
                    MediaQuery.of(context).size.height -
                    kToolbarHeight -
                    MediaQuery.of(context).padding.top,
                margin: EdgeInsets.only(
                  left: 12.w,
                  top: 5.h,
                  right: 12.w,
                  bottom: 20.h,
                ),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(MyImages.shareDetailBg),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Stack(
                  children: [
                    // 头像和用户信息
                    Positioned(
                      top: 10.h,
                      left: 19.w,
                      child: GestureDetector(
                        onTap: () {
                          final userId = shareAuthor?.id ?? '';
                          if (userId.isNotEmpty) {
                            context.push('${AppRoutes.userInfo}/$userId');
                          }
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            UserAvatar(
                              radius: 20.r,
                              avatarPath: shareAuthor?.avatar,
                              fallbackAsset: MyImages.kina,
                            ),
                            SizedBox(width: 5.w),
                            Text(
                              shareAuthor?.username ?? 'Unknown',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                                fontFamily: 'Port',
                                fontWeight: FontWeight.w400,
                                height: 1,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                    // 浏览量和用户信息
                    Positioned(
                      right: 25.w,
                      top: 15.h,
                      child: Row(
                        children: [
                          // 浏览用户的头像
                          if (viewers.isNotEmpty) ...[
                            SizedBox(
                              width: (viewers.length * 15 + 15).w,
                              height: 30.h,
                              child: Stack(
                                children: [
                                  for (
                                    int i = 0;
                                    i < viewers.length && i < 3;
                                    i++
                                  )
                                    Positioned(
                                      left: (i * 15).w,
                                      child: CircleAvatar(
                                        radius: 15.r,
                                        backgroundImage: AssetImage(
                                          viewers[i].avatar,
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ),
                          ],

                          // 浏览量
                          Text(
                            '+${currentShare!.browses} Watch',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12.sp,
                              fontFamily: 'Pangram',
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),

                    // 分享内容区域（可滚动）
                    Positioned(
                      top: 60.h,
                      left: 19.w,
                      width: 318.w, // 固定内容区域宽度
                      bottom: 20.h,
                      child: SingleChildScrollView(
                        controller: _scrollController,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 分享图片/视频
                            currentShare!.hasVideo
                                ? LazyVideoPlayerWidget(
                                    videoPath: currentShare!.video,
                                    width: 318.w,
                                    height: 427.h,
                                    autoPlay: false,
                                    showControls: true,
                                  )
                                : Container(
                                    width: 318.w,
                                    height: 427.h,
                                    decoration: ShapeDecoration(
                                      image: DecorationImage(
                                        image: AssetImage(
                                          currentShare!.hasImage
                                              ? currentShare!.image
                                              : MyImages.mark,
                                        ),
                                        fit: BoxFit.fill,
                                      ),
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                      ),
                                    ),
                                  ),

                            SizedBox(height: 10.h),

                            // 分享描述
                            SizedBox(
                              width: 318.w,
                              child: Text(
                                currentShare!.description,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15.sp,
                                  fontFamily: 'inter',
                                  fontWeight: FontWeight.w400,
                                  height: 1.2,
                                ),
                              ),
                            ),

                            SizedBox(height: 15.h),

                            // 分割线
                            Container(
                              width: 318.w,
                              height: 1.h,
                              decoration: BoxDecoration(
                                color: Colors.white.withValues(alpha: 0.15),
                              ),
                            ),

                            SizedBox(height: 15.h),

                            // 评论列表
                            ...comments.map(
                              (comment) => _buildCommentItem(comment),
                            ),

                            // 底部间距
                            SizedBox(height: 20.h),
                          ],
                        ),
                      ),
                    ),

                    // 独立的滚动条，贴在背景右侧，始终可见
                    Positioned(
                      top: 60.h,
                      right: 8.w, // 贴近背景右侧
                      bottom: 25.h,
                      width: 6.w,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(3.r),
                        ),
                        child: AnimatedBuilder(
                          animation: _scrollController,
                          builder: (context, child) {
                            // 使用try-catch来安全地获取滚动信息
                            double scrollExtent = 0.0;
                            double currentScroll = 0.0;

                            try {
                              // 检查是否有客户端
                              if (_scrollController.hasClients) {
                                scrollExtent =
                                    _scrollController.position.maxScrollExtent;
                                currentScroll = _scrollController.offset;
                              }
                            } catch (e) {
                              // 如果获取失败，使用默认值
                              scrollExtent = 0.0;
                              currentScroll = 0.0;
                            }

                            if (scrollExtent <= 0) {
                              // 内容不需要滚动时，显示固定长度的滚动条
                              return Container(
                                margin: EdgeInsets.all(1.w),
                                child: Align(
                                  alignment: Alignment.topCenter,
                                  child: Container(
                                    height: 40.h, // 固定长度
                                    decoration: BoxDecoration(
                                      color: Colors.white.withValues(
                                        alpha: 0.3,
                                      ),
                                      borderRadius: BorderRadius.circular(2.r),
                                    ),
                                  ),
                                ),
                              );
                            }

                            // 计算thumb的位置（固定长度40.h）
                            final containerHeight =
                                MediaQuery.of(context).size.height - 130.h;
                            final maxThumbPosition = containerHeight - 110.h;
                            final thumbPosition =
                                (currentScroll / scrollExtent) *
                                maxThumbPosition;

                            return Stack(
                              children: [
                                Positioned(
                                  top: thumbPosition.clamp(
                                    0.0,
                                    maxThumbPosition,
                                  ),
                                  left: 1.w,
                                  right: 1.w,
                                  height: 40.h, // 固定长度
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: Colors.white.withValues(
                                        alpha: 0.7,
                                      ),
                                      borderRadius: BorderRadius.circular(2.r),
                                    ),
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                    ),

                    // 点赞按钮
                    Positioned(
                      top: 75.h,
                      right: 25.w,
                      child: GestureDetector(
                        onTap: _toggleLike,
                        child: Container(
                          width: 32.w,
                          height: 32.h,
                          decoration: ShapeDecoration(
                            image: DecorationImage(
                              image: AssetImage(MyImages.goodBg),
                              fit: BoxFit.contain,
                            ),
                            shape: OvalBorder(),
                          ),
                          child: isLiked
                              ? Icon(
                                  Icons.favorite,
                                  color: Colors.red,
                                  size: 18.sp,
                                )
                              : Icon(
                                  Icons.favorite_border,
                                  color: Colors.white,
                                  size: 18.sp,
                                ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // 评论输入区域（固定在底部，跟随键盘移动）
              Positioned(
                bottom: MediaQuery.of(context).viewInsets.bottom + 35.h,
                left: 12.w,
                right: 12.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 19.w),
                  child: Row(
                    children: [
                      // 输入框
                      Expanded(
                        child: Container(
                          height: 41.35.h,
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          decoration: ShapeDecoration(
                            color: Color(0xFFFDF9F2),
                            shape: RoundedRectangleBorder(
                              side: BorderSide(
                                width: 2.w,
                                color: Color(0xFFFF8C00),
                              ),
                              borderRadius: BorderRadius.circular(22.r),
                            ),
                          ),
                          child: TextField(
                            controller: _commentController,
                            focusNode: _focusNode,
                            style: TextStyle(
                              color: Color(0xFFFF8C00),
                              fontSize: 12.sp,
                              fontFamily: 'PingFang SC',
                              fontWeight: FontWeight.w400,
                            ),
                            decoration: InputDecoration(
                              hintText: 'Say something',
                              hintStyle: TextStyle(
                                color: Color(0xFFFF8C00).withValues(alpha: 0.6),
                                fontSize: 12.sp,
                                fontFamily: 'PingFang SC',
                                fontWeight: FontWeight.w400,
                              ),
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.symmetric(
                                vertical: 12.h,
                              ),
                            ),
                            maxLines: 1,
                            textInputAction: TextInputAction.send,
                            onSubmitted: (_) => _sendComment(),
                          ),
                        ),
                      ),

                      SizedBox(width: 10.w),

                      // 发送按钮
                      GestureDetector(
                        onTap: _sendComment,
                        child: Container(
                          width: 69.20.w,
                          height: 38.59.h,
                          decoration: ShapeDecoration(
                            color: Color(0xFFFF8C00),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22.r),
                            ),
                          ),
                          child: Center(
                            child: Text(
                              'send',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 14.sp,
                                fontFamily: 'PingFang SC',
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建评论项
  Widget _buildCommentItem(CommentEntity comment) {
    final commentUser = _getCommentUser(comment.userId);

    return Container(
      margin: EdgeInsets.only(bottom: 15.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户头像
          UserAvatar(
            radius: 15.r,
            avatarPath: commentUser?.avatar,
            fallbackAsset: MyImages.kina,
          ),

          SizedBox(width: 10.w),

          // 评论内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户名
                Text(
                  commentUser?.username ?? 'Unknown',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w600,
                  ),
                ),

                SizedBox(height: 4.h),

                // 评论文本
                Text(
                  comment.content,
                  style: TextStyle(
                    color: Colors.white.withValues(alpha: 0.8),
                    fontSize: 11.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w400,
                    height: 1.3,
                  ),
                ),

                SizedBox(height: 4.h),

                // 评论时间
                Text(
                  _formatCommentTime(comment.date),
                  style: TextStyle(
                    color: Colors.white.withValues(alpha: 0.5),
                    fontSize: 10.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 切换点赞状态
  Future<void> _toggleLike() async {
    if (shareId == null) {
      return;
    }

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Please login to like'),
          backgroundColor: Colors.red,
          duration: const Duration(milliseconds: 750),
        ),
      );
      return;
    }

    try {
      setState(() {
        isLiked = !isLiked;
      });

      // 更新用户的点赞列表
      final updatedLikes = List<String>.from(currentUser.like);
      if (isLiked) {
        if (!updatedLikes.contains(shareId)) {
          updatedLikes.add(shareId!);
        }
      } else {
        updatedLikes.remove(shareId);
      }

      // 创建更新后的用户对象
      final updatedUser = UserEntity(
        id: currentUser.id,
        username: currentUser.username,
        password: currentUser.password,
        avatar: currentUser.avatar,
        share: currentUser.share,
        isVip: currentUser.isVip,
        like: updatedLikes,
      );

      // 更新用户信息（包括保存到数据库和更新Provider）
      await ref.read(userProvider.notifier).updateUser(updatedUser);
    } catch (e) {
      // 如果保存失败，恢复状态
      setState(() {
        isLiked = !isLiked;
      });
      debugPrint('点赞失败: $e');
    }
  }

  /// 发送评论
  Future<void> _sendComment() async {
    final content = _commentController.text.trim();
    if (content.isEmpty || shareId == null) return;

    debugPrint('content: $content');

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Please login to comment'),
          backgroundColor: Colors.red,
          duration: const Duration(milliseconds: 750),
        ),
      );

      return;
    }

    try {
      // 创建新评论
      final newComment = CommentEntity(
        id: 'c${DateTime.now().millisecondsSinceEpoch}',
        content: content,
        userId: currentUser.id,
        date: DateTime.now().toIso8601String(),
      );

      debugPrint('newComment: $newComment');

      // 保存评论
      final success = await CommentService.addComment(newComment, shareId!);
      if (success) {
        // 清空输入框
        _commentController.clear();
        _focusNode.unfocus();

        // 重新加载评论
        await _loadShareData();

        // 滚动到最新评论（最上方）
        _scrollController.animateTo(
          0,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      }
    } catch (e) {
      debugPrint('发送评论失败: $e');
    }
  }

  /// 获取评论用户
  UserEntity? _getCommentUser(String userId) {
    final allUsers = UserService.getAllUsers();
    for (final user in allUsers) {
      if (user.id == userId) {
        return user;
      }
    }
    return UserEntity.defaultUsers.first;
  }

  /// 格式化评论时间
  String _formatCommentTime(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      final now = DateTime.now();
      final difference = now.difference(date);

      if (difference.inDays > 0) {
        return '${difference.inDays}d ago';
      } else if (difference.inHours > 0) {
        return '${difference.inHours}h ago';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}m ago';
      } else {
        return 'Just now';
      }
    } catch (e) {
      return 'Unknown';
    }
  }

  /// 显示礼物对话框
  void _showGiftDialog() {
    showModalBottomSheet<void>(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return GiftDialogWidget(
          recipientId: shareAuthor?.id,
          recipientName: shareAuthor?.username,
        );
      },
    );
  }

  /// 显示举报对话框
  void _showReportDialog() {
    if (shareId == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Unable to report this post'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return ReportDialog(
          targetId: shareId!,
          reportType: ReportType.post,
          title: 'Report Post',
          onReportSuccess: () {
            if (Navigator.canPop(context)) {
              context.goBack();
              ref.read(shareProvider.notifier).loadAllShares();
            } else {
              context.go(AppRoutes.main);
            }
          },
        );
      },
    );
  }
}
